import { userLogin } from '@/api/user.js'
import { Toast } from 'vant'
import { getItem,setItem } from '@/utils/storage'
import router from '@/router'

const  USER_KEY = 'user-token'

    const state = {
        tokenInfo: getItem(USER_KEY) 
    }
    const mutations = {
        saveToken (state,tokenInfo){
            state.tokenInfo = tokenInfo 
            // localStorage.setItem('user-token',JSON.stringify(tokenInfo))
            setItem(USER_KEY,tokenInfo)
        },
        removeLoginInfo (state) {
            state.tokenInfo = {}
        }
    }
    const actions = {
        async Login ({commit},loginInfo){
            try {
                const loginRes = await userLogin(loginInfo)
                console.log(loginRes);
                if(loginRes.status === 201){
                    Toast.success('登录成功')
                    router.back()
                    commit('saveToken',loginRes.data.data)
                } 
            } catch (error) {
                    console.log(error.response);
                    Toast.fail(error.response.data.message)
            }
        }
    }
    const getters =  {
        
    }
export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}